import axios from "axios";
import UserUtil from "./UserUtil";

const myAxios = axios.create({
  baseURL: "http://interview-api-t.itheima.net",
});

myAxios.interceptors.request.use(
  (config) => {
    // 拦截请求，在请求头中添加token
    // const user = JSON.parse(localStorage.getItem("user"));

    const user = UserUtil.getUser();
    console.log("user", user);
    if (user?.token) {
      config.headers.Authorization = `Bearer ${user.token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

myAxios.interceptors.response.use(
  (response) => {
    // 拦截响应，如果响应状态码为401，则跳转到登录页
    console.log("response", response);
    if (response.status === 401) {
      console.log("401");
      localStorage.removeItem("user");
      window.location.href = "/login";
    }
    return response;
  },
  (error) => {
    console.log("error", error);
    if (error.status === 401) {
      console.log("401");
      localStorage.removeItem("user");
      window.location.href = "#/login";
      return;
    }
    return Promise.reject(error);
  }
);

export default myAxios;
